/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.datatheorem.ohos.trustkit.pinning;

import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.Set;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;


class DebugOverridesTrustManager {

    public static X509TrustManager getInstance(Set<Certificate> debugCaCerts) throws
            CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException {
        X509TrustManager debugTrustManager = null;

        KeyStore systemKeyStore = KeyStore.getInstance("AndroidCAStore");
        systemKeyStore.load(null, null);
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        Enumeration aliases = systemKeyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            X509Certificate cert = (X509Certificate) systemKeyStore.getCertificate(alias);
            keyStore.setCertificateEntry(alias , cert);
        }

        // Add the extra debug CAs to the store
        for (Certificate caCert : debugCaCerts) {
            String alias = "debug: " + ((X509Certificate) caCert).getSubjectDN().getName();
            keyStore.setCertificateEntry(alias , caCert);
        }

        // Create a TrustManager that trusts the CAs in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
        trustManagerFactory.init(keyStore);
        trustManagerFactory.getTrustManagers();

        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                debugTrustManager = (X509TrustManager) trustManager;
            }
        }

        if (debugTrustManager == null) {
            throw new IllegalStateException("Should never happen");
        }
        return debugTrustManager;
    }
}
